package com.xexun.gpstracker.baby.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;

import org.simple.eventbus.Subscriber;

import com.xexun.gpstracker.CommHandler;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.base.BaseActivity;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.fix.grant.PermissionsManager;
import com.xexun.gpstracker.fix.grant.PermissionsResultAction;
import com.xexun.gpstracker.pojo.Device;
import com.xexun.gpstracker.service.BlueToothService;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.Cmd;
import com.xexun.gpstracker.vo.CmdType;
import com.xexun.gpstracker.vo.Msg;
import com.xexun.gpstracker.vo.Session;


/**
 * Created by longchao on 2015/9/1 0001.
 * 蓝牙防偷的activity
 */
public class RemoteListenerActivity extends BaseActivity implements View.OnClickListener {

    private final static String TAG = RemoteListenerActivity.class.getSimpleName();


    private boolean listenerState = false; //监听状态
    int point = 0;

    private static final int CONSTATE_NORMAL = 0; //初始状态，未连接
    private static final int CONSTATE_SUCCESS = 1; //连接成功
    private static final int CONSTATE_FAIL = 2;//连接失败
    private static final int CONSTATE_CYCLEEND = 3; //一个搜索周期结束
    private static final int CONSTATE_DISCONNECT = 4; //蓝牙断开
    public static final String BLE_LOG_INFO = "ble_log_info";
    private boolean handlerOpen = false;


    private ImageButton backBtn;
    private ImageButton phoneBtn;
    private TextView bleStateTV, bleLog, titleNameTV;
    private TextView bleDesTV;
    private CheckBox bleStateCB;
    private ImageView bleHeadIV;
    private LinearLayout phoneLinear;
    private String imei;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_listener);
        assignViews();
        init();

        imei=getIntent().getStringExtra("IMEI");

        bleLog.setText("");

        bleDesTV.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        phoneBtn.setOnClickListener(this);


    }


    private void assignViews() {
        backBtn = (ImageButton) findViewById(R.id.backBtn);
        phoneBtn = (ImageButton) findViewById(R.id.phoneBtn);
        bleStateTV = (TextView) findViewById(R.id.bleStateTV);
        bleDesTV = (TextView) findViewById(R.id.bleDesTV);
        bleStateCB = (CheckBox) findViewById(R.id.bleStateCB);
        bleHeadIV = (ImageView) findViewById(R.id.bleHeadIV);
        bleLog = (TextView) findViewById(R.id.bleLog);
        titleNameTV = (TextView) findViewById(R.id.titleNameTV);
        phoneLinear = (LinearLayout) findViewById(R.id.phoneLinear);
    }


    private void init() {
        bleDesTV.setOnClickListener(this);
        bleStateTV.setText(getString(R.string.close_remote_listener));
        startService(new Intent(RemoteListenerActivity.this, BlueToothService.class));
        bleDesTV.setText(getString(R.string.remote_listener_succ));
        bleDesTV.setVisibility(listenerState ? View.VISIBLE : View.GONE);
        phoneLinear.setVisibility(listenerState ? View.VISIBLE : View.GONE);
//        bleStateCB.setChecked(mBluetoothAdapter.isEnabled());
        bleStateCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bleStateCB.isChecked()) { //这个时候是没有勾选上，则点击后勾选

                    remoteOpenListener();  //进来就先发一个命令

                } else {

                    remoteCloseListener();
                }
            }
        });
        bleStateCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) { //勾选上了就开启蓝牙
                    bleStateTV.setText(getString(R.string.open_remote_listener));

                } else { //否则就关闭蓝牙
                    bleStateTV.setText(getString(R.string.close_remote_listener));
                }
            }
        });

    }


    /**
     * 开启终端的蓝牙
     */
    private void remoteOpenListener() {
        //每次进入界面，先发一个命令开启终端蓝牙
        WizardAlertDialog.getInstance().showProgressDialog(R.string.please_later, RemoteListenerActivity.this, false);
        String phone = Session.getInstance().getUser().getPhone();
        Cmd cmd = new Cmd(CmdType.RC.getType(), "1," + phone, ChatActivity.mEntityImei, true); //1为开启蓝牙
        CommUtil.sendMsg(CommHandler.SEND_COMMAND, cmd);
        //setBleLogText("远程开启蓝牙命令已发");
        handlerOpen = true;
        handler.postDelayed(update_thread, 15000);
    }

    private void remoteCloseListener() {
        listenerState = false;
        bleDesTV.setVisibility(listenerState ? View.VISIBLE : View.GONE);
        phoneLinear.setVisibility(listenerState ? View.VISIBLE : View.GONE);
        handlerOpen = false;
        Log.d(Constants.TAG, "点这里，不勾选");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backBtn:
                RemoteListenerActivity.this.finish();
                break;
            case R.id.bleDesTV:

                break;
            case R.id.phoneBtn:
                onPhoneButtonClick();
                break;


        }
    }


    //@OnClick(R.id.phoneBtnChat)
    private void onPhoneButtonClick() {
        //打电话
        bleStateCB.performClick();
        //remoteCloseListener();
        Device device = Session.getInstance().getDevice(imei);

        if (device == null) {
            return;
        }
        final String phoneNumber = device.getPhone();
        if (TextUtils.isEmpty(phoneNumber)) {
            Toast.makeText(RemoteListenerActivity.this, R.string.phone_num_null, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utils.isMobileNO(phoneNumber)) {
            Toast.makeText(RemoteListenerActivity.this, R.string.phone_num_err, Toast.LENGTH_SHORT).show();
            return;
        }
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,
                new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
                new PermissionsResultAction() {
                    @Override
                    public void onGranted() {

                        Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
                        startActivity(phoneIntent);
                    }

                    @Override
                    public void onDenied(String permission) {
                        CommUtil.showMsgShort(String.format(getString(R.string.permission_refuse_comm_note), getString(R.string.permission_refuse_call_note)));
                    }
                });
    }


    private void setBleLogText(String string) {
        String text = (String) bleLog.getText();
        text = text + "\n" + string;
        bleLog.setText(text);
    }


    @Subscriber(tag = Constants.EVENT_TAG_REMOTE_LISTENER)
    private void startListener(Msg msg) {
        if (msg == null || msg.getFrom() == null) {
            return;
        }
        handlerOpen = false;
        listenerState = true;
        bleDesTV.setText(getString(R.string.remote_listener_succ));
        bleDesTV.setVisibility(listenerState ? View.VISIBLE : View.GONE);
        phoneLinear.setVisibility(listenerState ? View.VISIBLE : View.GONE);
        WizardAlertDialog.getInstance().closeProgressDialog();
    }

    //使用handler时首先要创建一个handler
    Handler handler = new Handler();
    //要用handler来处理多线程可以使用runnable接口，这里先定义该接口
    //线程中运行该接口的run函数
    Runnable update_thread = new Runnable() {
        public void run() {
            if (handlerOpen) {
                handlerOpen = false;
                bleStateCB.setChecked(false);
                listenerState = false;
                bleDesTV.setVisibility(View.VISIBLE);
                bleDesTV.setText(R.string.remote_listener_failed);
                phoneLinear.setVisibility(View.GONE);
                WizardAlertDialog.getInstance().closeProgressDialog();
            }

        }
    };
}